import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Tooltip,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  DatePicker,
  Select,
  Drawer,
  Col,
  Row
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import debounce from 'lodash/debounce'
import {ellipsis,afterCloseModal,DescriptionItem,todayLastSecond} from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEdit from './AddOrEdit'
import Info from './Info'
import AddOrEditDevice from '../Devices/AddOrEditDevice';

const FormItem = Form.Item;
const { confirm } = Modal;

const RadioButton = Radio.Button;
const Option = Select.Option;
const RadioGroup = Radio.Group;

@connect(({offline_command_logs, loading}) => ({
  offline_command_logs,
  loading: loading.models.offline_command_logs,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'device_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'device_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {
    this.changeTableY()
    const {dispatch} = this.props;
    const {
      offline_command_logs: {pageLoaded, scrollData},
    } = this.props;
    console.log('pageLoaded', pageLoaded)
    const table = document.querySelector('.ant-table-body')
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0)

    } else {
      const {
        offline_command_logs: {searchParams},
      } = this.props;
      console.log('searchParams', searchParams)
      dispatch({
        type: 'offline_command_logs/fetch',
        payload: searchParams,
        callback: ()=> {
          const {dispatch} = this.props;
          dispatch({
            type: 'offline_command_logs/changeLoaded',
          })
        }
      });
    }

    window.addEventListener('resize', this.resize)
    table.addEventListener('scroll', debounce(this.scroll, 150))
  }

  scroll = (e)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'offline_command_logs/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop
      },
    })
  }

  resize = ()=> {
    this.changeTableY()
  }

  changeTableY = ()=> {
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top - 50
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table = document.querySelector('.ant-table-body')
    table.removeEventListener('scroll', debounce(this.scroll, 300))
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'offline_command_logs/fetch',
      payload: {
        ...values,
      },
      callback () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      offline_command_logs: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
      <FormItem label={'开始时间'}>
          {getFieldDecorator('started_at', {
            initialValue: moment(searchParams.started_at),
          })(
            <DatePicker
              showTime
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD HH:mm:ss"
            />
          )}
        </FormItem>
        <FormItem label={'结束时间'}>
          {getFieldDecorator('ended_at', {
            initialValue: moment(searchParams.ended_at),
          })(
            <DatePicker
              showTime
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD HH:mm:ss"
            />
          )}
        </FormItem>
        <FormItem label={<span>
          设备ID&nbsp;
          <Tooltip title="需传递完整设备ID，非模糊匹配">
            <Icon type="question-circle-o" />
          </Tooltip>
        </span>}>
          {getFieldDecorator('device_id', {
            initialValue: searchParams.device_id,
          })(<Input style={{width:'170px'}} placeholder="请输入完整设备ID" />)}
        </FormItem>
         <FormItem label="类型">
          {getFieldDecorator('type',{
            initialValue: searchParams.type,
          })(
               <Select style={{width:'100px'}}>
                { [{key:'0',value:'全部'},{key:'1',value:'读'},{key:'2',value:'写'},{key:'3',value:'执行'}].map(item => <Option key={item.key} value={item.key}>{item.value}</Option>) }
              </Select>
        
          )}
        </FormItem>
        <FormItem label="状态">
          {getFieldDecorator('status',{
            initialValue: searchParams.status,
          })(
                 <Select style={{width:'100px'}}>
                { [{key:'0',value:'全部'},{key:'1',value:'命令等待'},{key:'2',value:'命令取消'},{key:'3',value:'下发成功'},{key:'4',value:'下发失败'}].map(item => <Option key={item.key} value={item.key}>{item.value}</Option>) }
              </Select>
        
          )}
        </FormItem>
        
      
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              this.handleSearch({
                page: 1,
                per_page: this.state.per_page,
                ...fieldsValue,
                started_at: moment(fieldsValue.started_at).format("YYYY-MM-DD HH:mm:ss"),
                ended_at: moment(fieldsValue.ended_at).format("YYYY-MM-DD HH:mm:ss"),
              })

            });
          }}
          >
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Button
            icon="ant-cloud"
            style={{marginLeft: 8}}
            type="primary"
            onClick={
            ()=> {
              this.setState({
                addModal: true
              })
            }
          }
          >
            下发缓存命令
          </Button>

        </FormItem>

      </Form>
    );
  }

  handleAdd = ()=> {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'offline_command_logs/add',
      payload: {
        ...formValues,
        content:formValues.type==='2'?this.AddForm.state.data:formValues.content,
        valid_at: moment(formValues.valid_at).format("YYYY-MM-DD HH:mm:ss"),
        expire_at: moment(formValues.expire_at).format("YYYY-MM-DD HH:mm:ss")
      },
      callback () {
        message.success('下发即时命令成功')
        that.setState({
          addModal: false,
        });
        const {
          offline_command_logs: {searchParams},
        } = that.props;
        that.handleSearch({
          ...searchParams,
          ended_at: moment(new Date(),"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss"),
        });
      }
    });
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      started_at:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss"),
      ended_at: todayLastSecond(),
      status:'0',
      device_id:'',
      type:'0',
      page: 1,
      per_page: 30,
    })
  }
  handleDelete = id => {
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: `offline_command_logs/remove`,
      payload: {id},
      callback: ()=> {
        message.success('缓存命令取消成功')
        const {
          offline_command_logs: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  renderStatus = (val) => {
    let type=""; let color=""; let text="";
    switch (val){
      case 1:
        type="clock-circle", color="#2d91eb", text="命令等待";
        break
      case 2:
        type="stop", color="#c46a07", text="命令取消";
        break
      case 4:
        type="close-circle", color="#eb2f96", text="下发失败";
        break
      case 3:
        type="check-circle", color="#52c41a", text="下发成功";
        break
      default:
        break
    }
    return  <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color} />{text}</Fragment>
  };
  renderType = (val) => {
    let type="";
    switch (val){
      case 1:
        type="读"
        break
      case 2:
        type="写"
        break
      case 3:
        type="执行"
        break
      default:
        break
    }
    return  <Fragment> {type}</Fragment>
  };
  render() {
    const that=this;
    const {
      offline_command_logs: {data, loading, meta, searchParams, selectedRowKeys},
    } = this.props;
    const columns = [
      {
        title: '创建时间',
        dataIndex: 'created_at',
        fixed:'left',
        width: 160,
        render: (val, record)=> ellipsis(val, 150)
      },
     {
        title: '设备ID',
        width: 180,
        dataIndex: 'device_id',
        fixed:'left',
        render: (val, record)=> 
           ellipsis(val, 165)

      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 130,
        render(val) {
          return that.renderStatus(val)
        },
      },
      {
        title: '类型',
        dataIndex: 'type',
        width: 120,
        render(val) {
          return that.renderType(val)
        }
      },

      {
        title: '对象ID',
        dataIndex: 'object_id',
        render: (val, record)=> ellipsis(val, 100)
      },
      {
        title: '操作',
        width: 120,
        fixed:'right',
        render: (val, record, index) =><Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              this.setState({
                editRecord: record,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            record.status===1&&
            <Button
              type="danger"
              size="small"
              onClick={(e)=> {
                e.stopPropagation()
                confirm({
                  title: `确定要取消"${record.device_id}"下发命令吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable:true,
                  onOk() {
                    that.handleDelete(record.id)
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >取消
            </Button>
          }
        </Fragment>
      },
    ];
    const rowSelection = {
      columnWidth: 40,
      selectedRowKeys,
      columnTitle: ' ',
      onChange: (selectedRowKeys) => {
        this.props.dispatch({
          type: 'offline_command_logs/changeSelectRow',
          payload: selectedRowKeys,
        })
      },
    };
    return <div className="custom-card">
      <div className="table-title">缓存命令列表</div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <Table
          style={{color: '#fff'}}
          className="custom-small-table"
          loading={loading}
          rowKey="id"
          dataSource={data}
          columns={columns}
          pagination={false}
          size="small"
          scroll={{x: true, y: this.state.tableY}}
          rowSelection={rowSelection}
          onRow={(record) => ({
            onClick: () => {
              this.props.dispatch({
                type: 'offline_command_logs/selectRow',
                payload: record,
              })
            },
          })}
        />

      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}} meta={meta} handleSearch={this.handleSearch} />
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="下发缓存命令" />}
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        className="addModal"
        onCancel={()=> {
          this.setState({addModal: false})
        }}

      >
        <AddOrEdit
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal" title={`${  this.state.editRecord.device_id} 下发内容`} />}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={()=> {
          this.setState({editModal: false, editRecord: {}})
        }}
        className="editModal"
        afterClose={()=>{
          afterCloseModal() // destroyOnClose需要
        }}
        onCancel={()=> {
          this.setState({editModal: false, editRecord: {}})
        }}

      >
        <Info
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
      <Drawer
        title={`${this.state.editRecord.device_id} 详情`}
        placement="right"
        closable={false}
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
          });
        }}
        width={500}
        visible={this.state.infoModal}
      >
        <Row>
          <Col span={12}>
            {
              DescriptionItem({
                title: '创建时间',
                content: this.state.editRecord.created_at,
              })
            }
          </Col>
          <Col span={12}>
            {
              DescriptionItem({
                title: '设备ID',
                content: this.state.editRecord.device_id,
              })
            }
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            {
              DescriptionItem({
                title: '在线状态',
                content: this.renderStatus(this.state.editRecord.status),
              })
            }
          </Col>
          <Col span={12}>
            {
              DescriptionItem({
                title: '订阅设备资',
                content: this.renderType(this.state.editRecord.type),
              })
            }
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            {
              DescriptionItem({
                title: '对象ID',
                content: this.state.editRecord.object_id,
              })
            }
          </Col>
          <Col span={12}>
            {
              DescriptionItem({
                title: '实例ID',
                content: this.state.editRecord.instance_id,
              })
            }
          </Col>
          <Col span={12}>
            {
              DescriptionItem({
                title: '资源ID',
                content: this.state.editRecord.resource_id,
              })
            }
          </Col>
          <Col span={12}>
            {
              DescriptionItem({
                title: '超时时间(秒)',
                content: this.state.editRecord.timeouts	,
              })
            }
          </Col>
          <Col span={24}>
            {
              DescriptionItem({
                title: '执行结果',
                content: JSON.stringify(this.state.editRecord.result)	,
              })
            }
          </Col>
          <Col span={24}>
            <p
              style={{
                marginRight: 8,
                display: 'inline-block',
                color: 'rgba(0,0,0,0.95)',
              }}
            >
              内容:
            </p>
            <Info
              editRecord={this.state.editRecord}
            />
          </Col>
        </Row>
      </Drawer>
    </div>
  }
}

export default BasicList;
